package net.maku.framework.security.config;

import net.maku.framework.security.exception.SecurityAuthenticationEntryPoint;
import net.maku.framework.security.mobile.*;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.DefaultAuthenticationEventPublisher;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private OncePerRequestFilter authenticationTokenFilter;
    @Resource
    private PermitResource permitResource;

    @Resource(name="userDetailsServiceImpl")
    private UserDetailsService userDetailsService;

    @Resource
    private MobileUserDetailsService mobileUserDetailsService;
    @Resource
    private MobileVerifyCodeService mobileVerifyCodeService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @Bean
    PcAuthenticationProvider pcAuthenticationProvider() {
        PcAuthenticationProvider pcAuthenticationProvider = new PcAuthenticationProvider();
        pcAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        pcAuthenticationProvider.setUserDetailsService(userDetailsService);

        return pcAuthenticationProvider;
    }


    @Bean
    MobileAuthenticationProvider mobileAuthenticationProvider() {
        return new MobileAuthenticationProvider(mobileUserDetailsService, mobileVerifyCodeService);
    }

    @Bean
    public AuthenticationManager authenticationManager() {
        List<AuthenticationProvider> providerList = new ArrayList<>();
        providerList.add(pcAuthenticationProvider());
        providerList.add(mobileAuthenticationProvider());

        ProviderManager providerManager = new ProviderManager(providerList);
        providerManager.setAuthenticationEventPublisher(new DefaultAuthenticationEventPublisher(applicationEventPublisher));

        return providerManager;
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        //添加放行路径，不需要走拦截链
//        web.ignoring().antMatchers(
//                //swagger2接口文档需要放行的路径
//                "/doc.html",
//                "/webjars/**",
//                "/swagger-resources/**",
//                "/v2/api-docs/**",
//                "/ws/**"
//        );
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        List<String> permitList = permitResource.getPermitList();
        String[] permits = permitList.toArray(new String[0]);
        http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                //关闭csrf
                .csrf().disable()
                .exceptionHandling(exception -> exception.authenticationEntryPoint(new SecurityAuthenticationEntryPoint()))
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(permits).permitAll()//登录
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();
    }
}
